package com.md.api.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.md.api.common.utils.AESUtil;
import com.md.api.common.utils.StringUtils;
import com.md.api.common.utils.TokenUtil;
import com.md.api.common.utils.UrlUtil;
import com.md.api.dao.ShareRecordMapper;
import com.md.api.dao.UserMapper;
import com.md.api.dao.VisitRecordMapper;
import com.md.api.entity.HttpResult;
import com.md.api.entity.ShareRecord;
import com.md.api.entity.UserInfo;
import com.md.api.entity.VisitRecord;
import com.md.api.entity.dto.ComposeQueryDto;
import com.md.api.entity.util.Page;
import com.md.api.service.ShareSevice;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.net.URLEncoder;
import java.util.*;

/**
 * @Author liujie
 * @ClassName PhotoServiceImpl
 **/

@Slf4j
@Service
public class ShareServiceImpl implements ShareSevice {

    @Resource
    TokenUtil tokenUtil;
    @Resource
    ShareRecordMapper shareRecordMapper;
    @Resource
    VisitRecordMapper visitRecordMapper;
    @Value("${common-key}")
    String commonKey;


    @Override
    public HttpResult visitRecord(HttpServletRequest request, ComposeQueryDto qto) {
        Page page = qto.getPage();
        page.initPagingData(VisitRecord.class);
        String userId = tokenUtil.getUserId(request);
        List<VisitRecord> list = visitRecordMapper.getByUserId(userId);
        page.setResult(list);
        return new HttpResult(page);
    }

    @Override
    public HttpResult shareDeail(HttpServletRequest request, ComposeQueryDto qto) {
        ShareRecord byShareId = shareRecordMapper.getByShareId(qto.getShareId());
        if (null==byShareId){
            return HttpResult.fail("暂无分享记录！");
        }
        boolean hasVisited = false;
        String userId = tokenUtil.getUserId(request);
        //记录访问记录
        if (StringUtils.isNotEmpty(userId)) {
            VisitRecord byUserIdAndShareId = visitRecordMapper.getByUserIdAndShareId(userId, qto.getShareId());
            if (null == byUserIdAndShareId) {
                VisitRecord vr = new VisitRecord();
                vr.setShareId(qto.getShareId());
                vr.setVisitUserId(userId);
                visitRecordMapper.insert(vr);
            }else{
                hasVisited = true;
            }
        }
        if(!byShareId.getShareUserId().equals(userId)||StringUtils.isEmpty(userId)) {
            shareRecordMapper.plusVisitCount(qto.getShareId());
        }
        return HttpResult.fail("暂无相关记录！");
    }



    @Override
    public HttpResult saveShare(HttpServletRequest request, ShareRecord shareRecord)  {
        String userId = tokenUtil.getUserId(request);
        shareRecord.setShareUserId(userId);
        String shareId = UUID.randomUUID().toString().replaceAll("-", "").toLowerCase();
        shareRecord.setShareId(shareId);
        JSONObject reqMap = new JSONObject();
        reqMap.put("shareId",shareId);
        reqMap.put("shareType",shareRecord.getShareType());
        reqMap.put("visitType","custom");
//        PhotoInfo dbPhoto = photoMapper.getByPhotoId(shareRecord.getSthIds());
//        if (null!=dbPhoto&&StringUtils.isNotEmpty(dbPhoto.getCoverImageUrl())) {
//            reqMap.put("coverImageUrl", dbPhoto.getCoverImageUrl());
//        }
        Map<String,String> resultMap = new HashMap();
        try {
            String customGetParam = URLEncoder.encode(AESUtil.encrypt(UrlUtil.jsonToGet(reqMap.toJSONString()),commonKey),"UTF-8");
            reqMap.put("visitType","sponsor");
            String sponsorGetParam = URLEncoder.encode(AESUtil.encrypt(UrlUtil.jsonToGet(reqMap.toJSONString()),commonKey),"UTF-8");
            String customUrl = shareRecord.getHtmlUrl()+"?"+customGetParam;
            String sponsorUrl = shareRecord.getHtmlUrl()+"?"+sponsorGetParam;
            shareRecord.setShareUrl(customUrl+";"+sponsorUrl);
            shareRecordMapper.saveShare(shareRecord);

            resultMap.put("custom",customUrl);
            resultMap.put("sponsor",sponsorUrl);
        }catch (Exception e){
            e.printStackTrace();
        }
        return new HttpResult(resultMap);
    }



    public static void main(String[] args) {

        System.out.println(AESUtil.decrypt("9yBV+NeqSHtB9JRJCWFZiW5nIYbb1EFziVmVBT7iCfeFyPRTnil3iNMck/y/yOpn2Xj+qB2QhadH6LcwDaqu6r82iU2zJz+CX8L90kONQ+w=","7c24mhsuqzrgssb5"));


    }
}
